<?php
namespace App\Http\Controllers\Web\User;

use App\Http\Controllers\Web\BaseController;
use App\Services\Cookie\Carts;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Http\Request;
use Jenssegers\Agent\Facades\Agent;
use Illuminate\Support\Facades\Cookie;

class RegisterNewController extends BaseController
{
    protected  $api_url = [
        'login' => ['get', 'user/login'],
        'sendmessage' => ['get', 'sendmessage'], 
        'checkphone' => ['get', 'user/checkphone'],
        'checkusername' => ['get', 'user/checkusername'],
        'verifycode' => ['get', 'verifycode'],
        'backpwd' => ['get', 'user/backpwd'],
        'cate' => ['get', 'cate'],
        'companyregisternew' => ['post', 'user/companyregisternew'],
        'personalregister' => ['post', 'user/personalregister'],
        'add_carts'=> ['post', 'buyer/carts/add_carts'],
        'verify_im'=> ['post', 'im/verify'], // 登录成功后验证账号是否有 IM 账号

    ];


    protected $request;

    public function __construct(Request $request)
    {
        //设备类型
         if (Agent::isTablet()) {
          // 平板
             $equipment = 'Tablet';
         } else if (Agent::isMobile()) {
          // 便捷设备
             $equipment = 'Mobile';
         } else if (Agent::isRobot()) {
          // 爬虫机器人
             $equipment = 'Robot';
         } else {
          // 桌面设备
             $equipment = 'Desktop';
         }

        $this->request = $request;
        $this->ip = $request->getClientIp() ? $request->getClientIp() : '127.0.0.1';
        $this->logn_equipment = $equipment;
        $this->to_url = '/member/user/info';
    }






    //注册视图页
    public function registerAction(Request $request){
        if (session('user_id'))
            return redirect($this->to_url);

        $request->session()->forget('register_session');//清除企业注册第一步所存session
        return view('web.login.register_new');
    }





    /*
    * 个人注册信息提交
    */
    public function personalRegisterAction(Request $request)
    {
        $this->validate($this->request, [
            'personal_phone' => 'required|string',
            'personal_code' => 'required|string',
            'personal_pwd' => 'required|string',
            'agree' => 'required|string',
            'personal_enterprise' => 'required|string',
        ]);


        //验证验证码是否填写正确
        $param_code = ['phone' => $request->input('personal_phone'),'code' => $request->input('personal_code')];
        $data_code = http_web($this->api_url['verifycode'])->send($param_code);
        if($data_code['code'] != 0){
            return $data_code;
        }

        $params = [
            'phone' => $request->input('personal_phone'),
            'name' => $request->input('personal_phone'),
            'pwd' => $request->input('personal_pwd'),
            'code' => $request->input('personal_code'),
            'personal_enterprise' => $request->input('personal_enterprise'),
        ];


            //个人注册
            $data = http_web($this->api_url['personalregister'])->send($params);

            if($data['code']==0){

                $all = $this->request->all('uname','pwd');

                //请求部分
                $postzhi = array('username' => $request->input('personal_phone'), 'pwd' => $request->input('personal_pwd'),'ip' => $this->ip,'logn_equipment' => $this->logn_equipment);
                $data = http_web($this->api_url['login'])->send($postzhi);

                if ($data['code'] == 0) {

                    //将登陆信息注入session
                    session([
                        'user_id' => $data['data']['id'],
                        'user_phone' => $data['data']['phone'],
                        'user_name' => $data['data']['name'],
                        'user_email' => $data['data']['email'],
                        'user_shop_id' => $data['data']['shop_id'],
                        'user_is_test_user' => $data['data']['is_test_user'],
                        'user_identification_type' => $data['data']['identification_type'],
                        'user_personal_enterprise' => $data['data']['personal_enterprise'],
                        'user_b2b_token' => $data['data']['user_token'],
                        //'usertoken' => $old_data['data']['token'],
                        'user_info' => $data['data'],
                        'user_im_token' => isset($im['data']['data']['token'])?$im['data']['data']['token']:false,
                        'user_im_name' => isset($im['data']['data']['accid'])?$im['data']['data']['accid']:false,
                        //'userinfo' => $old_data['data']
                    ]);

                }

            }
            return $data;


    }


     /*
     * 个人注册第二步
     */
    public function personalRegisterTwoAction()
    {
        return view('web.login.register_per_two');
    }

    /*
    * 企业注册第二步
    */
    public function companyRegisterTwoAction(Request $request)
    {

        if ($request->session()->has('register_session')) {
            $sekey = $request->session()->get('register_session');
            return view('web.login.register_com_two')->with($sekey);
        }else{

            $this->validate($this->request, [
                'phone' => 'required|string',
                'pwd' => 'required|string',
                'code' => 'required|string',
                'agree' => 'required|string',
                'personal_enterprise' => 'required|string',
            ]);

            //验证验证码是否填写正确
            $param_code = ['phone' => $request->input('phone'),'code' => $request->input('code')];
            $data_code = http_web($this->api_url['verifycode'])->send($param_code);
            if($data_code['code'] != 0){
                return $data_code;
            }

            $params = [
                'phone' => $request->input('phone'),
                'pwd' => $request->input('pwd'),
                'personal_enterprise' => $request->input('personal_enterprise'),
            ];


            //企业注册第一步（将相关信息存入session用于企业注册第二步）
            $request->session()->put('register_session', $params);
            $data['code'] = 0;
            return $data;

        }

    }




    /*
    * 企业注册信息提交
    */
    public function companyRegisterAction(Request $request)
    {

        $this->validate($this->request, [
            'name' => 'required|string',
            'company_type' => 'required|string',
            'phone' => 'required|string',
            'pwd' => 'required|string',
        ]);


        //参数

        $params = [
            'phone' => $request->input('phone'),
            'pwd' => $request->input('pwd'),
            'company_name' => $request->input('name'),//公司名称
            'ent_type' => json_encode(array_filter(explode(',', $request->input('company_type')))), //公司类型
            'organization_code' => $request->input('organizationCode'),//组织机构代码
            'personal_enterprise' => $request->input('personal_enterprise'),//企业账号
            'company_address' => $request->input('province_text').$request->input('city_text'),//公司地址
        ];

        $data = http_web($this->api_url['companyregisternew'])->send($params);

        if($data['code']==0){
            $request->session()->forget('register_session');//清除企业注册第一步所存session

            //请求部分
            $postzhi = array('username' => $request->input('phone'), 'pwd' => $request->input('pwd'),'ip' => $this->ip,'logn_equipment' => $this->logn_equipment);
            $data = http_web($this->api_url['login'])->send($postzhi);

            if ($data['code'] == 0) {

                //将登陆信息注入session
                session([
                    'user_id' => $data['data']['id'],
                    'user_phone' => $data['data']['phone'],
                    'user_name' => $data['data']['name'],
                    'user_email' => $data['data']['email'],
                    'user_shop_id' => $data['data']['shop_id'],
                    'user_is_test_user' => $data['data']['is_test_user'],
                    'user_identification_type' => $data['data']['identification_type'],
                    'user_personal_enterprise' => $data['data']['personal_enterprise'],
                    'user_b2b_token' => $data['data']['user_token'],
                    //'usertoken' => $old_data['data']['token'],
                    'user_info' => $data['data'],
                    'user_im_token' => isset($im['data']['data']['token'])?$im['data']['data']['token']:false,
                    'user_im_name' => isset($im['data']['data']['accid'])?$im['data']['data']['accid']:false,
                    //'userinfo' => $old_data['data']
                ]);

            }

        }

        return $data;

    }



    /*
     * 企业注册第三步
     */
    public function companyRegisterThreeAction()
    {
        return view('web.login.register_com_three');
    }






    /*
    *发送短信
    */
    public function sendmessagesAction(Request $request)
    {
        $phone = $request->input('phone');
        if (!preg_match("/^1[34578]\d{9}$/", $phone)) {
            $data['code'] = '1';
            $data['message'] = '手机号码格式不正确';
        } else {
            //验证是否注册
            $param = ['phone' => $phone];
            $data = http_web($this->api_url['checkphone'])->send($param);

            if ($data['data'] === 902) {
                //发送短信验证
                $data_send = http_web($this->api_url['sendmessage'])->send($param);

                return $data_send;

            } else {
                $data['code'] = '1';
                $data['message'] = $data['message'];
            }

        }
        return response()->json($data);

    }








    /*
    *注册短信发送，判断方式和其他发送短信相反
    */
    public function registermessagesAction(Request $request)
    {
        $phone = $request->input('phone');
        if (!preg_match("/^1[34578]\d{9}$/", $phone)) {
            $data['code'] = '1';
            $data['message'] = '手机号码格式不正确';
        } else {
            //验证是否注册
            $param = ['phone' => $phone];
            $data = http_web($this->api_url['checkphone'])->send($param);

            if ($data['data'] === 903) {
                //发送短信验证
                $data_send = http_web($this->api_url['sendmessage'])->send($param);

                return $data_send;

            } else {
                $data['code'] = '1';
                $data['message'] = $data['message'];
            }

        }
        return response()->json($data);

    }








}